package cn.iocoder.yudao.module.mqtt.framework.interceptor;

import cn.iocoder.yudao.module.mqtt.framework.util.MqttContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.stereotype.Component;

/**
 * MQTT消息拦截器
 * 在消息处理前添加客户端ID和配置ID信息
 *
 * @author 芋道源码
 */
@Slf4j
@Component
public class MqttMessageInterceptor implements ChannelInterceptor {

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        try {
            // 从消息头中获取客户端ID和配置ID
            String clientId = null;
            Long configId = null;
            
            if (message.getHeaders().get("mqtt_receivedClientId") != null) {
                clientId = message.getHeaders().get("mqtt_receivedClientId").toString();
            }
            if (message.getHeaders().get("mqtt_configId") != null) {
                configId = Long.valueOf(message.getHeaders().get("mqtt_configId").toString());
            }
            
            // 设置到线程本地变量
            if (clientId != null) {
                MqttContextHolder.setClientId(clientId);
                log.debug("拦截器设置客户端ID: {}", clientId);
            }
            if (configId != null) {
                MqttContextHolder.setConfigId(configId);
                log.debug("拦截器设置配置ID: {}", configId);
            }
            
        } catch (Exception e) {
            log.warn("MQTT消息拦截器处理异常", e);
        }
        
        return message;
    }

    @Override
    public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
        // 清理线程本地变量
        MqttContextHolder.clear();
    }
} 